<template>
  <div class="container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" id="mybg">
      <el-row>
        <el-col :span='7'>
          <el-input placeholder="请输入内容" v-model="input" clearable class="in" @keyup.enter.native="seluser"
            @clear='getuser'>
            <el-button slot="append" icon="el-icon-search" @click='seluser'>搜索
            </el-button>
          </el-input>
        </el-col>
        <el-col :span='3' style="position: absolute; right: -10px;">
          <el-button type="primary" icon="el-icon-circle-plus-outline" v-permission="{action:'add'}"
            @click='dialogVisible = true'>添加用户</el-button>
        </el-col>
      </el-row>
      <!--  数据表格 -->
      <el-table :data="tableData" border style="width: 100%;">
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">
            <div>
              {{scope.$index+(currentPage - 1) * pageSize + 1}}
            </div>
          </template>
</el-table-column>
<el-table-column prop="username" label="用户名" width="120">
</el-table-column>
<el-table-column prop="password" label="密码" width="205">
</el-table-column>
<el-table-column prop="age" label="年龄" width="100">
</el-table-column>
<el-table-column prop="sex" label="性别" width="100">
</el-table-column>
<el-table-column prop="tel" label="手机号" width="145">
</el-table-column>
<el-table-column prop="email" label="邮箱" width="170">
</el-table-column>
<el-table-column prop="dz" label="当前用户登录地址" width="294">
</el-table-column>
<el-table-column prop="jurisdiction" label="权限" width="145">
</el-table-column>
<el-table-column prop="state" label="登录状态" width="125">
    <template v-slot="scope">
            <el-switch v-model='scope.row.state' active-color="#13ce66" inactive-color="#ff4949" disabled></el-switch>
          </template>
</el-table-column>
<el-table-column label="操作" width="185">
    <template v-slot='scope'>

            <el-tooltip effect="dark" content="修改" placement="top" :enterable='false'>
              <el-button type="primary" :disabled="scope.row.username == 'admin'" icon="el-icon-edit" circle size='mini'
                @click='showEditDialog(scope.row.id)' v-permission="{action:'edit'}">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable='false'>
              <el-button type="primary" icon="el-icon-delete" circle size='mini' style="color: red !important;"
                @click="open(scope.row)" :disabled="scope.row.username == 'admin'"
                v-permission="{action:'delete',effect:'disabled'}">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="查看用户位置" placement="top" :enterable='false'>
              <el-button type="primary" icon="el-icon-location" circle size='mini' @click='ckdt(scope.row)'>
              </el-button>
            </el-tooltip>
          </template>
</el-table-column>
</el-table>
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-sizes="[1,2,3,5,10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background>
</el-pagination>
</el-card>
<!-- 添加用户框 -->
<el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
    <el-form :model="addruleForm" :rules="addFormrules" ref="addruleFormref" label-width="70px" class="demo-ruleForm" style="width: 450px;">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="addruleForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addruleForm.password" show-password clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
            <el-input v-model="addruleForm.age" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="addruleForm.sex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
            <el-input v-model="addruleForm.tel" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="addruleForm.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="jurisdiction">
            <el-radio-group v-model="addruleForm.jurisdiction">
                <el-radio label="超级管理员"></el-radio>
                <el-radio label="审核员"></el-radio>
                <el-radio label='普通员'></el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="adduser" :loading="logining">添加</el-button>
      </span>
</el-dialog>
<!-- 修改对话框 -->
<el-dialog title="修改用户" :visible.sync="EditDialogVisible" width="40%" @close='editDiaclose'>
    <el-form :model="EditDialog" :rules="EditDialogrules" ref="EditDialogFormref" label-width="70px" class="demo-ruleForm" style="width: 450px;">
        <el-form-item label="用户名">
            <el-input v-model="EditDialog.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码">
            <el-input type="password" v-model="EditDialog.password" show-password clearable disabled>
            </el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
            <el-input v-model="EditDialog.age" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="EditDialog.sex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
            <el-input v-model="EditDialog.tel" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="EditDialog.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="jurisdiction" v-permission="{action:'delete'}">
            <el-radio-group v-model="EditDialog.jurisdiction">
                <el-radio label="超级管理员"></el-radio>
                <el-radio label="审核员"></el-radio>
                <el-radio label='普通员'></el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser" :loading="logining">确 定</el-button>
      </span>
</el-dialog>
<!-- 查看用户位置框 -->
<el-dialog title="用户位置" :visible.sync="dt" width="70%">
    <div id="container" style="height: 600px;">

    </div>
</el-dialog>

</div>
</template>

<script>
    var map

    export default {
        data() {

            return {
                //搜索框值
                input: '',
                logining: false,
                //添加用户框显示隐藏
                dialogVisible: false,

                //添加用户表单数据
                addruleForm: {
                    username: '',
                    password: '',
                    age: '',
                    sex: '',
                    tel: '',
                    email: '',
                    jurisdiction: ''
                },
                //添加表单验证
                addFormrules: {
                    username: [{
                        required: true,
                        message: '请输入用户名',
                        messtrigger: 'blur',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^(\w){4,12}$/,
                        message: '只能输入4-12个字母、数字、下划线 ',
                        trigger: 'blur'
                    }],
                    password: [{
                        required: true,

                        message: '请输入密码',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/,
                        message: '最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符',
                        trigger: 'blur'
                    }],
                    age: [{
                        required: true,
                        message: '请输入年龄',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^[0-9]+$/,
                        message: '请输入数字',
                        trigger: 'blur'
                    }],
                    sex: [{
                        required: true,
                        message: '请选择性别',
                        trigger: 'change'
                    }],
                    tel: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号',
                        trigger: 'blur'
                    }],
                    email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/,
                        message: '请输入正确的邮箱',
                        trigger: 'blur'
                    }],
                    jurisdiction: [{
                        required: true,
                        message: '请选择权限',
                        trigger: 'change'
                    }]
                },
                //地图
                position: ['111.718557', ' 27.045352'],
                dt: false,


                //修改用户的对话框显示和隐藏
                EditDialogVisible: false,
                //修改用户数据
                EditDialog: {},
                EditDialogrules: {
                    age: [{
                        required: true,
                        message: '请输入年龄',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^[0-9]+$/,
                        message: '请输入数字',
                        trigger: 'blur'
                    }],
                    sex: [{
                        required: true,
                        message: '请选择性别',
                        trigger: 'change'
                    }],
                    tel: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号',
                        trigger: 'blur'
                    }],
                    email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, {
                        required: true,
                        pattern: /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/,
                        message: '请输入正确的邮箱',
                        trigger: 'blur'
                    }],
                    jurisdiction: [{
                        required: true,
                        message: '请选择权限',
                        trigger: 'change'
                    }]
                },
                //数据表格值
                tableData: [],
                //分页
                currentPage: 1, // 当前页
                total: 0, // 数据总条数
                pageSize: 5 // 每页条数
            }
        },
        created() {
            this.getuser();
            this.currentPage = Number(localStorage.getItem('pagination')) || 1;
            this.handleCurrentChange(this.currentPage)
        },
        beforeUpdate() {
            localStorage.setItem('pagination', this.currentPage)
        },
        beforeDestroy() {
            localStorage.setItem('pagination', 1)
        },
        mounted() {
            this.createBg()
        },
        methods: {
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                        this.$refs.addruleFormref.resetFields()
                    })
                    .catch(_ => {});
            },
            createBg() {
                /* eslint-disable */
                // console.log(VANTA)
                VANTA.BIRDS({
                    el: '#mybg',
                    mouseControls: true,
                    touchControls: true,
                    gyroControls: false,
                    minHeight: 200.00,
                    minWidth: 200.00,
                    scale: 1.00,
                    scaleMobile: 1.00,
                    // backgroundColor: 0x70e2f
                    backgroundColor: '#fff'
                })
            },

            getuser() {
                let pageSize = this.pageSize
                let currentPage = this.currentPage
                this.$axios.get('/api/userlist', {
                    params: {
                        pageSize,
                        currentPage,

                    }
                }).then(res => {

                    this.tableData = res.data.data.result;
                    //将字段值进行映射后再展示
                    this.tableData.map(v => (v.state = v.state === 1 ? true : false))
                    this.total = res.data.data.count
                })
            },
            // 每页显示条数改变 就会触发这个函数
            handleSizeChange(val) {
                // 保存每页显示的条数
                this.pageSize = val;
                this.getuser()
                this.seluser()
            },
            // 当前页码改变 就会触发这个函数
            handleCurrentChange(val) {
                // 保存当前页码
                this.currentPage = val;
                this.getuser()
                this.seluser()
            },
            //查询
            seluser() {
                if (this.input !== '') {
                    this.$axios.get('/api/seluser', {
                        params: {
                            inputs: this.input,
                            pageSize: this.pageSize,
                            currentPage: this.currentPage
                        }
                    }).then(res => {

                        this.tableData = res.data.result
                            //将字段值进行映射后再展示
                        this.tableData.map(v => (v.state = v.state === 1 ? true : false))
                        this.total = res.data.count
                    })
                } else {
                    this.getuser()
                }
            },
            //添加用户
            adduser() {
                this.$refs.addruleFormref.validate(valid => {
                    if (valid) {
                        this.logining = true;
                        let _this = this;
                        //发送添加请求
                        setTimeout(() => {
                            this.$axios({
                                method: 'post',
                                url: `api/adduser`,
                                data: {
                                    username: _this.addruleForm.username,
                                    password: _this.addruleForm.password,
                                    age: _this.addruleForm.age,
                                    sex: _this.addruleForm.sex,
                                    tel: _this.addruleForm.tel,
                                    email: _this.addruleForm.email,
                                    jurisdiction: _this.addruleForm.jurisdiction
                                }
                            }).then(res => {
                                console.log(res.data);
                                if (res.data.data !== '添加成功') {
                                    this.$message.error(res.data.data);
                                } else {
                                    this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    });
                                    this.dialogVisible = false;
                                    this.getuser()
                                }
                                this.logining = false;
                            }).catch(error => {
                                console.log(error);
                            });
                        }, 1000);
                    } else {
                        this.$message.error("表单校验失败，请检查");
                        return false;
                    }
                })
            },
            //编辑用户
            showEditDialog(id) {
                this.EditDialogVisible = true;
                this.$axios.get(`api/userlist/${id}`).then(res => {
                    if (res.data.status !== 200) {
                        this.$notify.error({
                            title: '错误',
                            message: h('i', {
                                style: 'color: red'
                            }, '信息获取失败')
                        });
                    } else {
                        this.EditDialog = res.data.data
                    }
                })
            },
            //关闭编辑表单重置
            editDiaclose() {
                this.$refs.EditDialogFormref.resetFields()
            },
            //提交修改
            editUser() {
                this.$refs.EditDialogFormref.validate(valid => {
                    if (valid) {
                        this.logining = true;
                        setTimeout(() => {
                            this.$axios.put(`api/edit/${this.EditDialog.id}`, {
                                age: this.EditDialog.age,
                                tel: this.EditDialog.tel,
                                sex: this.EditDialog.sex,
                                email: this.EditDialog.email,
                                jurisdiction: this.EditDialog.jurisdiction
                            }).then(res => {
                                if (res.data.data !== '修改成功') {
                                    this.$message.error(res.data.data);
                                } else {
                                    this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    this.EditDialogVisible = false
                                    this.getuser()
                                    this.seluser()
                                }
                                this.logining = false;
                            }).catch(error => {
                                console.log(error);
                            });
                        }, 1000);
                    } else {
                        this.$message.error("表单校验失败，请检查");
                        return false;
                    }
                })
            },
            //删除
            open(del) {
                this.$confirm(`此操作将永久删除该用户${del.username}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete(`/api/userlist/${del.id}`).then(res => {
                        if (res.data.status == 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getuser()
                            this.seluser()
                        } else {
                            this.$message.error("删除失败");
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //绘制地图
            init() {
                map = new AMap.Map('container', {
                        center: this.position,
                        zoom: 16,
                    })
                    //创建一个marker
                var marker = new AMap.Marker({ //在地图上显示自己的位置标记
                    position: this.position, //marker所在的位置
                    map: map //创建时直接赋予map属性

                });
                AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
                    map.addControl(new AMap.ToolBar())
                    map.addControl(new AMap.Scale())
                })
            },
            //查看地图
            ckdt(dts) {
                this.dt = true
                console.log(dts);
                this.position = [dts.lng, dts.lat]
                this.init()
            }
        }
    }
</script>

<style scoped lang="less">
    .text {
        font-size: 14px;
    }
    
    .item {
        padding: 18px 0;
    }
    
    .container {
        height: 100%;
    }
    
    .box-card {
        width: 100%;
        height: 98%;
    }
    
    /deep/.el-table th,
    /deep/.el-table tr {
        background-color: rgba(255, 255, 255, 0);
    }
    
    .el-table,
    .el-table__expanded-cell {
        background-color: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-table tbody tr:hover>td {
        background-color: rgba(46, 64, 102, .5);
    }
    
    /deep/.el-input__inner {
        background-color: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-button {
        background: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-input-group__append {
        background-color: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-button--primary {
        color: #409BFF !important;
        border-color: #DCDFE6;
    }
    
    /deep/.el-pagination {
        background-color: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-pagination .btn-prev {
        background-color: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-pagination .btn-next {
        background-color: rgba(255, 255, 255, 0);
    }
    
    /deep/.el-pagination .el-pager li {
        background-color: rgba(255, 255, 255, 0);
    }
</style>